package com.ccrfid.rmc6.service.sys;

import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.appconfig.exception.pojo.CustomErrors;
import com.ccrfid.rmc6.entity.sys.UploadFileEntity;
import com.ccrfid.rmc6.repository.search.SearchCriteria;
import com.ccrfid.rmc6.repository.sys.UploadFileRepository;
import com.ccrfid.rmc6.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class UploadFileServiceImpl implements UploadFileService {

    @Autowired
    private UploadFileRepository uploadFileRepository;

    @Value("${file.upload.folder}")
    private String fileUploadFolder;

    @Override
    public Page<UploadFileEntity> searchFile(SearchCriteria criteria, Pageable pageable) {
        return uploadFileRepository.search(criteria, pageable);
    }

    @Override
    public UploadFileEntity uploadFile(String fileName, InputStream inputStream, String userAccount, String clientIp)
            throws IOException {
        File file = new File(fileUploadFolder + '/' + fileName);
        File parent = file.getParentFile();
        //创建目录
        if (!parent.exists()) {
            parent.mkdirs();
        }
        //保存文件
        FileUtils.copyInputStreamToFile(inputStream, file);
        //保存上传记录
        UploadFileEntity fileEntity = uploadFileRepository.getFirstByFileName(fileName);
        if (fileEntity == null) {
            fileEntity = new UploadFileEntity();
        }
        fileEntity.setFileName(fileName);
        fileEntity.setUserAccount(userAccount);
        fileEntity.setClientIp(clientIp);
        return uploadFileRepository.save(fileEntity);
    }

    @Override
    public File downloadFile(Long fileId) throws AppException {
        UploadFileEntity fileEntity = uploadFileRepository.getById(fileId);
        if (fileEntity == null) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        File file = new File(fileUploadFolder + '/' + fileEntity.getFileName());
        if (!file.exists()) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        return file;
    }

    @Override
    public File downloadFile(String fileName) throws AppException {
        File file = new File(fileUploadFolder + '/' + fileName);
        if (!file.exists()) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        return file;
    }

    @Override
    public void deleteFiles(List<Long> idList) {
        if (idList != null && idList.size() > 0) {
            for (Long id : idList) {
                UploadFileEntity fileEntity = uploadFileRepository.getById(id);
                if (fileEntity != null) {
                    deleteFile(fileEntity.getFileName());
                    uploadFileRepository.deleteById(id);
                }
            }
        }
    }

    private boolean deleteFile(String fileName) {
        File file = new File(fileUploadFolder + '/' + fileName);
        if (file.exists()) {
            String timeStr = DateUtil.toDateTimeStr2(new Date());
            return file.renameTo(new File(fileUploadFolder + '/' + fileName + '.' +  timeStr + ".deleted"));
        }
        return false;
    }
}
